#!/usr/bin/perl -w

# This is search.pl, part of Picture Bank.  search.pl looks for stuff 
#+ according to map file and the descriptions it contains.  It allows 
#+ AND-wise and OR-wise searches.
# See the files README, LICENCE and Changelog for more info.

# Copyright (C) 2007 Alexis Phoenix

# url we were given; something like
# search.pl?map=./config/test.map&or=false&terms=this+that+other

use CGI;
use CGI::Pretty;
$config_path="/usr/lib/cgi-bin/config/";
#$config_path="/home/alexis/picture-bank/config";

$query=new CGI;
$map=$query->param("map") or $map="";
$or=$query->param("or") or $or="off";
$term_list=$query->param("terms") or $term_list="";

@terms=split(" ","$term_list");

$ME='search.pl';
$THUMBS='thumbs.pl';

print $query->header(),
      $query->start_html(-title=>'Search'),
      $query->h3('Perform Search'),
      $query->p([
      $query->start_form(-method=>'post',action=>"$ME"),
      $query->textfield(-name=>'terms',value=>"$term_list").'&nbsp;Enter/edit search terms here',
      $query->textfield(-name=>'map',value=>"$map").'&nbsp;Enter album name if required',
      $query->checkbox(-name=>'or',default=>'off',label=>'').'&nbsp;Default search type is "AND", tick box for an "OR" type search',
      $query->submit(-value=>'Search!').'&nbsp',
      $query->reset(value=>'Clear Form'),
              'Result']);

open(MAP, "<$config_path$map") or print "could not open map file</body></html>" && exit;
while(<MAP>) {
  unless (m/:ignore/||m/:new/) {
    push (@lines, $_)
  }
}
close (MAP);

if ($or eq "on") {  # should this be "on" or "true" or "or"?
  print $query->p('performed an "OR" type search');
  foreach (@terms) {
    push (@rows,&search($_,@lines))  ## pick up lines containing any of the terms
  }
  @lines=@rows
}
else {
  print $query->p('performed an "AND" type search');
  foreach (@terms) {
    @lines=search($_,@lines)  ## pick up lines containing all of the terms
  }
}

if (scalar(@lines)==0) {
  print $query->p('Sorry, I could not find the thing you wanted');
  print $query->end_html;
  exit
}

## added code to make gallery list

@gname=("");
$n=0;
print $query->start_table({border=>'1'}),  ## make a nicely laid out listing of results
      $query->th({span=>'2'},'Directories found');
#print "</td></tr><tr><th span=\"2\">Directories found</th></tr>";
foreach (@lines) { #lines is now search result
  print "<tr>";
  @words=split(" ",$_);
  $path=shift(@words);
  if (m/(:gallery\S+)/) {  # do this in case of "gallery" being a 
    $word=$1;              #+ search term rather than a keyword
 #   ($word=~s/://);
    @bits=split("-",$word);
    print "<td>Found in gallery $bits[1]</td>";
#    print "<td>".join(": ",@bits)."</td>";
    for ($n=0;$n<=$#gname;$n++) {
 #   print "gname n is $gname[$n] n is $n and word is $word\n";
      if ($gname[$n]=~m/$word/) {
        $gname[$n]="$gname[$n]".'+'."$path"  # create an array of gallery names with paths
      }
      else {
        $gname[$n]="$word"."="."$path"
      }
    }
  }
  else {
    print "<td>".join(", ",@words)."</td>"; # search terms in line with result
  }
  print "<td><a href=$THUMBS?map=$map&paths=$path>$path</a></td></tr>\n";
}
unless ($gname[0] eq "") {
  print "<th span=\"2\">Galleries retrieved:</th>";
  foreach (@gname) {
    @name=split("=",$_);
    print "<tr><td></td><td><a href=$THUMBS?map=$map"."&"."$_>$name[0]</a></td></tr>"  # could refine $name[0]
  }
}
print "<tr><th span=\"2\">Collective result:</th></tr><tr><td span=\"2\">";
all(@lines);
print "</table>";


print <<END;
</body>
</html>
END

sub search {
  my @result=();
  my $term=shift @_;
  foreach $item (@_) {
    @bits=split(/ /,$item);
    shift @bits; # get rid of path to prevent matches to path elements
    $pieces=join(" ",@bits);
    if ($pieces=~m/$term/) {
      push (@result, $item)
    }
  }
  return (@result)
}

sub all {  ## routine to create one link to produce thumbs of everything
  my @lines=@_;
  my $seen="";

  $galleries=join('&',@gname);
#  print "galleries in all: $galleries\n";
  foreach (@lines) {
   @words=split(/ /,$_);
   
#  foreach (@lines) {
#    @words=split(/ /,$_);
#    if (m/(:gallery\S+)/) {
#      my $line=join(" ",($1, $words[0]));  # gives (gal,/path/)
#      push (@gals, $line)
#    }
#    else {
#      if (defined($paths)) {
#        $paths="$paths"."+"."$words[0]"
#      }
#      else {
#        $paths="$words[0]"
#      }
#    }
#  }

    unless (m/(:gallery\S+)/){ # changed the else to unless
      if (defined($paths)) {
        $paths="$paths"."+"."$words[0]"
      }
      else {
        $paths="$words[0]"
      }
    }
  }
  unless (defined($paths)) {
    $paths="";  # need to pick up the cases where $paths creation was skipped
    $pflag=0
  }
  else {
    $paths="paths=$paths";
    $pflag=1
  }
#  @gals=sort(@gals);
#  foreach (@gals) {
#    @words=split(" ",$_);
#    unless ($words[0] eq $seen) {  # in other words, unless we're already on this gallery
#      $seen=$words[0];  # set $seen to be the gallery name
#      if (defined($list)) {
#        $list="$list"."&"."$seen"."="."$words[1]"; # just string it all together
#      }
#      else {
#        $list="$seen"."="."$words[1]"
#      }
#    }
#    else {
#       $list="$list"."+"."$words[1]"
#    }
#  }
#  unless (defined($list)) {
#    $list=""  # pick up cases where $list creation was skipped
#  }
#  else {
#    if ($pflag==1) {
#      $list="$list"."&"  # only need ampersand if $paths exists
#    }
#  }
#  print "\n\n<a href=$THUMBS?map=$map"."&"."$list$paths".">Show all results</a>\n\n";
  unless ($galleries eq "") {
    if ($pflag==1) {
      $galleries="$galleries"."&"  # only need ampersand if $paths exists
    }
  }
 # else {
 #   $galleries=""  # pick up cases where $list creation was skipped
 # }
  print "\n\n<a href=$THUMBS?map=$map"."&"."$galleries$paths".">Show all results</a>\n\n";
}
